<template>
  <view class="home-container">
    <!-- 顶部导航栏 -->
    <up-navbar :safeAreaInsetTop="true" :fixed="true" :border="false" bgColor="#e2f7f1" placeholder>
      <template #left>
        <view class="navbar-left">
          <view class="logo">
            <image class="logo-image" src="@/static/logo2.png" mode="aspectFit"></image>
          </view>
        </view>
      </template>

      <template #center>
        <view class="segment-control">
          <view class="segment-item" :class="{ active: activeTab === 'nexa' }" @click="activeTab = 'nexa'">MasterCard</view>
          <view class="segment-item" :class="{ active: activeTab === 'web3' }" @click="activeTab = 'web3'">Web3</view>
        </view>
      </template>

      <template #right>
        <u-icon name="bell" size="20" color="#333"></u-icon>
      </template>
    </up-navbar>

    <!-- MasterCard 内容 -->
    <view v-if="activeTab === 'nexa'">
      <!-- 当前余额卡片 -->
      <!-- <view class="balance-card">
        <view class="balance-header">
          <text class="balance-label">Current Balance</text>
        </view>
        <view class="balance-amount">
          <text class="amount">0.00 USDT</text>
        </view>
        <view class="balance-change">
          <u-icon name="arrow-up" size="12" color="#fff"></u-icon>
          <text class="change-text">0.0% from last month</text>
        </view>
        <view class="balance-dots">
          <view class="dot active"></view>
          <view class="dot"></view>
          <view class="dot"></view>
        </view>
      </view> -->

      <!-- 总资产估值 -->
      <!-- <view class="asset-section">
        <view class="asset-info">
          <view class="asset-header">
            <text class="asset-label">{{ useT('总资产估值') }}</text>
            <u-icon name="eye" size="16" color="#999"></u-icon>
          </view>
          <view class="asset-amount">
            <text class="amount">0.00</text>
            <text class="currency">USDT</text>
          </view>
          <view class="cny-amount">≈ ¥ 0.00</view>
        </view>
        <view class="recharge-btn" @click="handleRecharge">
          <text class="btn-text">{{ useT('充值') }}</text>
        </view>
      </view> -->

      <!-- Visa卡推广 -->
      <!-- <view class="visa-banner">
        <up-notice-bar text="如何申请visa实体卡" mode="link" fontSize="14" speed="60" url="/pagesD/about/about"></up-notice-bar>
      </view> -->

      <!-- 快速功能网格 -->
      <view class="quick-actions u-p-t-40">
        <view class="action-grid">
          <view class="action-item" v-for="(action, index) in quickActionsList" :key="index" @click="handleActionClick(action)">
            <view class="action-icon">
              <u-icon :name="action.icon" size="24" :color="action.color"></u-icon>
            </view>
            <text class="action-text">{{ action.name }}</text>
          </view>
        </view>
      </view>

      <!-- 美股行情 -->
      <view class="stock-section">
        <view class="section-header">
          <text class="section-title">{{ useT('美股行情') }}</text>
        </view>
        <view class="stock-table">
          <!-- 表头 -->
          <view class="table-header">
            <view class="header-cell name-header">{{ useT('代码/名称') }}</view>
            <view class="header-cell price-header">{{ useT('最新价格') }}</view>
            <view class="header-cell trend-header">{{ useT('趋势') }}</view>
          </view>
          <!-- 股票数据 -->
          <view class="stock-item" v-for="(stock, index) in stockData" :key="stock.id || index">
            <view class="stock-info">
              <view class="stock-logo">
                <image v-if="stock.logoUrl" :src="stock.logoUrl" mode="aspectFill" style="width: 100%; height: 100%; border-radius: 8rpx" />
                <text v-else class="logo-text">{{ (stock.symbol || stock.name || 'X').toString().charAt(0).toUpperCase() }}</text>
              </view>
              <text class="stock-name">{{ stock.displayName }}</text>
            </view>
            <view class="stock-price">
              <text class="price">{{ stock.price }}</text>
            </view>
            <view class="stock-trend">
              <view class="trend-icon" :class="stock.changeType">
                <u-icon :name="stock.changeIcon" size="12" :color="stock.changeColor"></u-icon>
              </view>
              <text class="trend-text" :style="{ color: stock.changeColor }">{{ stock.changePercent }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Web3 内容 -->
    <view v-if="activeTab === 'web3'" class="web3-container">
      <!-- Web3 钱包插画和内容 -->
      <view class="web3-content">
        <view class="web3-illustration">
          <!-- 3D钱包插画 -->
          <image src="@/static/home/web3.png" class="web3-image" mode="aspectFit"></image>
        </view>

        <view class="web3-text">
          <text class="web3-title">WEB3 钱包</text>
          <text class="web3-subtitle">钱包·交易·DeFi...</text>
        </view>
      </view>
    </view>

    <!-- 自定义 Tabbar -->
    <CustomTabbar :currentIndex="0" />
  </view>
</template>

<script setup>
import { getHomeMarket } from '@/api/project.js';
import { updateUserInfo } from '@/api/user.js';
import CustomTabbar from '@/components/CustomTabbar.vue';
import { useUserStore } from '@/stores/user.js';
import { useT } from '@/utils/i18n.js';
import { onHide, onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';

// 用户状态管理
const userStore = useUserStore();

// 快速功能数据
const quickActions = ref([
  { id: 'scan', name: '扫一扫', icon: 'scan', color: '#4A90E2' },
  { id: 'payment', name: '收款码', icon: 'grid', color: '#4A90E2' },
  { id: 'redpacket', name: '红包', icon: 'red-packet', color: '#FF6B6B' },
  { id: 'salary', name: '发薪/汇款', icon: 'coupon', color: '#4ECDC4' },
  { id: 'finance', name: '理财', icon: 'rmb-circle', color: '#45B7D1' },
  { id: 'partner', name: '合伙人', icon: 'account', color: '#96CEB4' },
  { id: 'invite', name: '邀请', icon: 'man-add', color: '#FECA57' },
  { id: 'nft', name: 'HTT&RWA', icon: 'grid', color: '#A55EEA' }
]);
const quickActionsList = computed(() => {
  return quickActions.value.map((item) => {
    return {
      ...item,
      name: useT(item.name)
    };
  });
});
// 当前选中的标签
const activeTab = ref('nexa');

// 美股数据
const stockData = ref([]);
// 行情轮询定时器
const marketTimer = ref(null);
onLoad(() => {
  uni.hideTabBar();
});
onShow(() => {
  if (userStore.isLoggedIn) {
    updateUserInfo();
    getHomeMarketData();
    // 开启每秒轮询
    if (marketTimer.value) {
      clearInterval(marketTimer.value);
    }
    marketTimer.value = setInterval(() => {
      getHomeMarketData();
    }, 1000);
  }
});
onHide(() => {
  if (marketTimer.value) {
    clearInterval(marketTimer.value);
    marketTimer.value = null;
  }
});
onUnload(() => {
  if (marketTimer.value) {
    clearInterval(marketTimer.value);
    marketTimer.value = null;
  }
});

// 获取首页行情
const getHomeMarketData = async () => {
  const res = await getHomeMarket();
  console.log('====>res', res);
  if (res.data && Array.isArray(res?.data) && res.data.length > 0) {
    const list = res.data;
    stockData.value = list.map((item) => {
      const change = Number(item?.price_change_percentage_24h ?? 0);
      const isUp = change >= 0;
      return {
        id: item?.id,
        symbol: item?.symbol?.toUpperCase?.() || '',
        name: item?.name || '',
        displayName: `${(item?.symbol || '').toUpperCase()}/${item?.name || ''}`,
        logoUrl: item?.logo || '',
        price: item?.current_price ?? '--',
        changePercent: `${isUp ? '+' : ''}${isFinite(change) ? change.toFixed(2) : 0}%`,
        changeType: isUp ? 'up' : 'down',
        changeIcon: isUp ? 'arrow-up' : 'arrow-down',
        changeColor: isUp ? '#4CAF50' : '#FF5252'
      };
    });
  }
};
// 处理快速功能点击
const handleActionClick = (action) => {
  switch (action.id) {
    case 'scan':
      uni.navigateTo({
        url: '/pagesA/scan/scan'
      });
      break;
    case 'payment':
      uni.navigateTo({
        url: '/pagesA/payment/payment'
      });
      break;
    case 'redpacket':
      uni.navigateTo({
        url: '/pagesA/redpacket/redpacket'
      });
      break;
    case 'salary':
      uni.navigateTo({
        url: '/pagesA/transfer/transfer'
      });
      break;
    case 'finance':
      uni.navigateTo({
        url: '/pagesA/finance/finance'
      });
      break;
    case 'partner':
		uni.showToast({
		  title: useT('功能升级中'),
		  icon: 'none'
		})
      // uni.navigateTo({
      //   url: '/pagesA/partner/partner'
      // });
      break;
    case 'invite':
      uni.navigateTo({ url: '/pagesA/invite/invite' });
      break;
    case 'nft':
      uni.showToast({
        title: useT('NFT&RWA功能暂未开放'),
        icon: 'none'
      });
      break;
    default:
      uni.showToast({
        title: useT('暂未开放'),
        icon: 'none'
      });
  }
};

// 充值处理函数
const handleRecharge = () => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    // 未登录，跳转到登录页面
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }
  if (userStore.userInfo.id_verify_status != 2) {
    // 未实名认证 跳转到实名认证页面
    uni.navigateTo({
      url: '/pagesA/identity/identity'
    });
    return;
  }
  if (userStore.userInfo.id_verify_status == 2) {
    // 已实名认证 跳转到充值页面
    uni.navigateTo({
      url: '/pagesA/recharge/recharge'
    });
    return;
  }
};

// 生命周期
onMounted(() => {
  console.log('首页加载完成');
});
</script>

<style lang="scss" scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #e2f7f1 20%, #f8f9fa 40%);
  padding-bottom: 120rpx; /* 为 tabbar 留出空间 */
}

// 导航栏样式
.navbar-left {
  display: flex;
  align-items: center;

  .logo {
    width: 60rpx;
    height: 60rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16rpx;
    overflow: hidden;

    .logo-image {
      width: 100%;
      height: 100%;
    }
  }
}

.segment-control {
  display: flex;
  background-color: #ecf9f8;
  border-radius: 24rpx;
  padding: 4rpx;

  .segment-item {
    padding: 12rpx 24rpx;
    font-size: 24rpx;
    color: #666;
    border-radius: 20rpx;
    transition: all 0.3s;

    &.active {
      background-color: #fff;
      color: #333;
      font-weight: 600;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
  }
}

// 当前余额卡片
.balance-card {
  margin: 32rpx auto;
  width: calc(100% - 48rpx);
  max-width: 686rpx;
  height: 320rpx;
  padding: 40rpx;
  background: linear-gradient(135deg, #12c284, #8059ff);
  border-radius: 60rpx;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;

  .balance-header {
    margin-bottom: 20rpx;
    text-align: center;

    .balance-label {
      color: rgba(255, 255, 255, 0.9);
      font-size: 28rpx;
      font-weight: 500;
    }
  }

  .balance-amount {
    margin-bottom: 20rpx;
    text-align: center;

    .amount {
      color: #fff;
      font-size: 56rpx;
      font-weight: bold;
      line-height: 1.2;
    }
  }

  .balance-change {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32rpx;

    .change-text {
      color: rgba(255, 255, 255, 0.9);
      font-size: 26rpx;
      margin-left: 8rpx;
    }
  }

  .balance-dots {
    display: flex;
    align-items: center;
    justify-content: center;

    .dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.3);
      margin-right: 12rpx;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        background-color: rgba(255, 255, 255, 0.8);
      }
    }
  }
}

// 总资产估值
.asset-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 32rpx 24rpx;
  padding: 32rpx;
  background-color: #fff;
  border-radius: 16rpx;

  .asset-info {
    .asset-header {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .asset-label {
        font-size: 28rpx;
        color: #333366;
        font-weight: 500;
        margin-right: 8rpx;
      }
    }

    .asset-amount {
      display: flex;
      align-items: baseline;
      margin-bottom: 8rpx;

      .amount {
        font-size: 48rpx;
        font-weight: bold;
        color: #333366;
        margin-right: 8rpx;
      }

      .currency {
        font-size: 28rpx;
        color: #333366;
        font-weight: 500;
      }
    }

    .cny-amount {
      font-size: 24rpx;
      color: #999;
    }
  }

  .recharge-btn {
    padding: 20rpx 32rpx;
    background: linear-gradient(90deg, #4a90e2, #12c284);
    border-radius: 24rpx;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 2rpx;
      left: 2rpx;
      right: 2rpx;
      bottom: 2rpx;
      background-color: #fff;
      border-radius: 22rpx;
    }

    .btn-text {
      color: #333366;
      font-size: 28rpx;
      font-weight: 600;
      position: relative;
      z-index: 1;
    }
  }
}

// Visa卡推广 - NoticeBar样式调整
.visa-banner {
  margin: 0 32rpx 32rpx;

  :deep(.up-notice-bar) {
    border-radius: 16rpx;
    overflow: hidden;
  }
}

// 快速功能网格
.quick-actions {
  margin: 0 32rpx 32rpx;

  .action-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 32rpx;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      border-radius: 16rpx;

      .action-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16rpx;
        background-color: #f8f9fa;
      }

      .action-text {
        font-size: 24rpx;
        color: #333;
        text-align: center;
        word-wrap: break-word;
        word-break: break-all;
        white-space: pre-wrap;
      }
    }
  }
}

// 美股行情
.stock-section {
  margin: 0 32rpx 32rpx;

  .section-header {
    margin-bottom: 24rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #2c3e50; // 深蓝紫色
    }
  }

  .stock-table {
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;

    .table-header {
      display: flex;
      background-color: #f8f9fa;
      padding: 20rpx 24rpx;
      border-bottom: 1rpx solid #e9ecef;

      .header-cell {
        font-size: 26rpx;
        font-weight: 600;
        color: #2c3e50; // 深蓝紫色

        &.name-header {
          flex: 1;
          text-align: left;
        }

        &.price-header {
          flex: 1;
          text-align: center;
        }

        &.trend-header {
          flex: 1;
          text-align: right;
        }
      }
    }

    .stock-item {
      display: flex;
      align-items: center;
      padding: 24rpx;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .stock-info {
        flex: 1;
        display: flex;
        align-items: center;

        .stock-logo {
          width: 40rpx;
          height: 40rpx;
          border-radius: 8rpx;
          background-color: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16rpx;

          .logo-text {
            font-size: 18rpx;
            font-weight: bold;
            color: #333;
          }
        }

        .stock-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }

      .stock-price {
        flex: 1;
        text-align: center;

        .price {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
        }
      }

      .stock-trend {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .trend-icon {
          margin-right: 8rpx;
        }

        .trend-text {
          font-size: 26rpx;
          font-weight: 500;
        }
      }
    }
  }
}
// Web3 界面样式
.web3-container {
  margin-top: 300rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .web3-content {
    text-align: center;
    .web3-illustration {
      margin-bottom: 60rpx;

      .web3-image {
        width: 300rpx;
        height: 300rpx;
        margin: 0 auto;
        display: block;
      }
    }

    .web3-text {
      .web3-title {
        display: block;
        font-size: 48rpx;
        font-weight: bold;
        color: #2c2c2c;
        margin-bottom: 20rpx;
        line-height: 1.3;
      }

      .web3-subtitle {
        display: block;
        font-size: 28rpx;
        color: #888888;
        font-weight: 400;
        line-height: 1.5;
      }
    }
  }
}
</style>
